package com.zshy.base.protocol.utils;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Maps;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;
import java.util.SortedMap;


public class HttpParamUtils {


    public static SortedMap<String, String> getAllParams(HttpServletRequest request) throws IOException {

        SortedMap<String, String> result = Maps.newTreeMap();
        Map<String, String> allRequestParam = Maps.newHashMap();
        // get请求不需要拿body参数
        if (!HttpMethod.GET.name().equals(request.getMethod())) {
            allRequestParam = getAllRequestParam(request);
        }
        //将URL的参数和body参数进行合并
        if (allRequestParam != null) {
            for (Map.Entry entry : allRequestParam.entrySet()) {
                result.put((String) entry.getKey(), entry.getValue().toString());
            }
        }
        return result;
    }


    public static Map<String, String> getAllRequestParam(final HttpServletRequest request) throws IOException {
        InputStream in = request.getInputStream();
        StringBuilder wholeStr = new StringBuilder();
        //一行一行的读取body体里面的内容；
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1; ) {
            wholeStr.append(new String(b, 0, n));
        }
        //转化成json对象
        return JSONObject.parseObject(wholeStr.toString(), Map.class);
    }


    public static Map<String, String> getUrlParams(HttpServletRequest request) {
        String param = "";
        try {
            if (StringUtils.isNotBlank(request.getQueryString())) {
                param = URLDecoder.decode(request.getQueryString(), "utf-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Map<String, String> result = Maps.newHashMap();
        String[] params = param.split("&");
        for (String s : params) {
            int index = s.indexOf("=");
            result.put(s.substring(0, index), s.substring(index + 1));
        }
        return result;
    }

    /**
     * 把json按照key 为字母的顺序放入到排序map中
     *
     * @param json
     * @return
     */
    public static SortedMap<String, Object> joinToSortMap(String json) {
        // 创建一个普通的Map，用于存储解析后的JSON数据
        Map<String, Object> allRequestParam = Maps.newHashMap();
        // 如果传入的JSON字符串不为空
        if (StringUtils.isNotBlank(json)) {
            // 使用JSON解析工具将JSON字符串解析成一个普通的Map对象
            allRequestParam = JSONObject.parseObject(json, Map.class);
        }
        // 返回排序后的Map
        return MapUtil.sortMapByKey(allRequestParam);
    }

}

